import {GptVersion} from "@/app/constants";
import {MessageRole} from "@/types/chat";
import {useAccessStore} from "@/app/store/access";
import {getServerSideConfig} from "@/app/config/server";

//zhishiconst {apiHostUrl} = getServerSideConfig();
const apiHostUrl = "http://localhost:8090";

/**
 * 获取头部信息
 */
function getHeader() {
    const accessState = useAccessStore.getState();
    const headers = {
        Authorization: accessState.token,
        'Content-Type': 'application/json;charset=utf-8'
    }
    return headers;
}

/**
 * 获取角色接口信息
 */
export const getRoleList = () => {
    return fetch(`/prompts.json`).then((res) => res.json());
}

/**
 *流式接口应答
 * @param data
 */
export const completions = (data: {
    messages: { content: string; role: MessageRole }[],
    model: GptVersion
}) => {
    return fetch(`${apiHostUrl}/api/v1/chat/completions`, {
        method: 'post',
        headers: getHeader(),
        body: JSON.stringify(data)
    })
}

/**
 * 登录鉴权接口
 */
export const login = (token: string) => {
    const accessState = useAccessStore.getState()
    return fetch(`${apiHostUrl}/api/v1/auth/login/${accessState.accessCode}`, {
        method: 'post',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
        }
    })
};

/**
 *商品列表查询
 */
export const queryProductList = () => {
    return fetch(`${apiHostUrl}/api/v1/sale/query/product/list`, {
        method: 'get',
        headers: getHeader()
    })
}

/**
 *用户商品下单，获得支付地址URL
 * @param productId  产品id
 */
export const createPayOrder = (productId: number) => {
    return fetch(`${apiHostUrl}/api/v1/sale/create/pay/order`, {
        method: 'post',
        headers: {
            ...getHeader(),
            "Content-Type": "application/x-www-form-urlencoded;charset=utf-8"
        },
        body: `productId=${productId}`
    })
}